<template>
  <div class="navigation-pane">
    <transition name="slide-fade">
      <div class="navigation-pane__panel" v-if="showPane">
        <ul>
          <li :class="[id === item.id ? 'navigation-pane__panel-item--active' : '','navigation-pane__panel-item']" v-for="item in nav" :key="item.id" @click="() => navigateTo(item)">
            {{
              item.title }}</li>
        </ul>
      </div>
    </transition>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
import type { Nav } from './navigation-pane';

@Component({
  name: 'navigation-pane',
})
export default class NavigationPane extends Vue {
  @Prop() nav!: Nav[];
  private get showPane() {
    return this.$store.state.showPane;
  }
  private id: string | null = '';
  private flag = false;
  private timer: NodeJS.Timeout | undefined = undefined;

  navigateTo(item: Nav) {
    this.flag = true;
    const element = document.getElementById(item.id);
    if (element === null) {
      return;
    }
    this.id = item.id;
    element.scrollIntoView({
      behavior: 'smooth',
    })
    this.timer = setTimeout(() => {
      this.flag = false;
    }, 800)
  }

  mounted() {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting && !this.flag && entry.intersectionRatio === 1) {
          console.log(entry.target.textContent, entry.intersectionRatio);
          const id = entry.target.getAttribute('id');
          this.id = id;
        }
      })
    }, {
      rootMargin: '0px 0px -80% 0px',
      threshold: 1
    });

    const ele = document.querySelectorAll('.doc__header');
    ele.forEach(item => {
      observer.observe(item);
    })

    const footer = document.querySelector('footer');
    const footerObserver = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        this.id = this.nav[this.nav.length -1].id;
      }
    }, {
      root: null,
      threshold: 0.1
    })
    if (footer) {
      footerObserver.observe(footer);
    }
  }

  destroyed() {
    console.log('destroyed document');
    clearTimeout(this.timer);
  }

}
</script>

<style lang="scss" scoped>
.navigation-pane {
  position: fixed;
  right: 10px;
  top: $safe-area-top + 34px;

  &__panel {
    background-color: #fefefe;
    border: 1px solid #e9e9e9;
    border-radius: 2px;
    max-width: 200px;
    min-width: 120px;
  }

  &__panel-item {
    line-height: 2.5;
    font-size: 12px;
    color: #565656;
    padding: 0 8px;
    border-bottom: 1px solid #e9e9e9;

    &:last-child {
      border-bottom: none;
    }

    &--active {
      color: #1989fa;
    }
  }
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all .5s ease;
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(12px);
  opacity: 0;
}
</style>
